using System.Collections.Generic;
using System.Text;

namespace BLL.Extensions
{
    /// <summary>
    /// Contains helper methods for the <see cref="string"/> class.
    /// </summary>
    public static class StringExtensions
    {
        /// <summary>
        /// Inserts space before every uppercase letter in the specified string.
        /// </summary>
        /// <param name="source">The source string to modify.</param>
        public static string SplitUpperCase(this string source)
        {
            if (string.IsNullOrWhiteSpace(source))
                return string.Empty;

            var words = new List<string>();
            int wordStartIndex = 0;

            char[] letters = source.ToCharArray();
            char previousChar = char.MinValue;

            // Skip the first letter. we don't care what case it is.
            for (int i = 1; i < letters.Length; i++)
            {
                if (char.IsUpper(letters[i]) && !char.IsWhiteSpace(previousChar))
                {
                    // Grab everything before the current index.
                    words.Add(new string(letters, wordStartIndex, i - wordStartIndex));
                    wordStartIndex = i;
                }

                previousChar = letters[i];
            }

            // We need to have the last word.
            words.Add(new string(letters, wordStartIndex, letters.Length - wordStartIndex));

            return string.Join(" ", words);
        }

        /// <summary>
        /// Returns bytes array that represent current string in UTF8 encoding.
        /// </summary>
        /// <param name="source">The source string to convert.</param>
        /// <returns>Bytes array that represent current string in UTF8 encoding.</returns>
        public static byte[] ToBytes(this string source)
        {
            return Encoding.UTF8.GetBytes(source);
        }
    }
}